<?php

declare(strict_types=1);

namespace App\Aspect;

use App\Service\SomeService;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Hyperf\Logger\LoggerFactory;
use Psr\Log\LoggerInterface;

/**
 * @Aspect
 */
class LogAspect extends AbstractAspect
{
    // 要切入的类或方法
    public array $classes = [
        SomeService::class . '::someMethod',
        SomeService::class . '::anotherMethod',
    ];

    private LoggerInterface $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        $this->logger = $loggerFactory->get('log');
    }

    public function process(ProceedingJoinPoint $proceedingJoinPoint)
    {
        // 方法执行前
        $this->logger->info('Before executing', [
            'method' => $proceedingJoinPoint->className . '::' . $proceedingJoinPoint->methodName,
            'arguments' => $proceedingJoinPoint->arguments['keys'],
        ]);

        try {
            // 执行原方法并获取结果
            $result = $proceedingJoinPoint->process();
            
            // 方法执行后
            $this->logger->info('After executing', [
                'result' => $result,
            ]);
            
            return $result;
        } catch (\Throwable $e) {
            // 异常处理
            $this->logger->error('Error executing', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
            
            throw $e;
        }
    }
}